<template>
  <div class="square">
    <div
      class="square-inner"
      :style="boxStyle"
    >
      <image
        :src="src"
        mode="aspectFill"
      ></image>
    </div>
    <div
      class="square-dummy"
      :style="dummyStyle"
    ></div>
    <div
      class="square-cover"
      :style="coverStyle"
      v-if="icon"
    >
      <div class="square-cover__icon">
        <div class="square-cover__icon-inner">
          <image
            :src="icon"
            mode="aspectFill"
          ></image>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ScaleImage',
  props: {
    ratio: {
      type: Number,
      default: 1
    },
    src: {
      type: String,
      default: '',
      required: true
    },
    icon: {
      type: String,
      default: ''
    },
    iconSize: {
      type: String,
      default: 'default'
    },
    radius: [Number, String]
  },
  data () {
    return {
      borderRadius: 0
    }
  },
  computed: {
    dummyStyle () {
      let ratio = 100
      if (this.ratio > 0) {
        ratio /= this.ratio
      }
      return `padding-top:${ratio}%`
    },
    boxStyle () {
      if (this.radius) {
        let radius = this.addUnit(this.radius)
        return `border-radius: ${radius}`
      }
      return ''
    },
    coverStyle () {
      if (!this.icon) {
        return ''
      }
      let top = 0
      if (this.ratio > 0) {
        top = (1 - this.ratio) / 2 * 100
      }
      let style = [
        `top:${top}%`
      ]
      if (this.iconSize === 'large') {
        style.push(`transform: scale(0.3)`)
      }
      return style.join(';')
    }
  },
  methods: {
    addUnit (value) {
      if (value) {
        return /^\d+(\.\d+)?$/.test(value) ? value + 'px' : value
      }
      return undefined
    }
  }
}
</script>

<style lang="less">
.square {
  position: relative;
  width: 100%;
  &-dummy {
    display: block;
    padding-top: 100%;
  }
  &-inner {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    -moz-box-align: center;
    -moz-box-pack: justify;
    align-items: center;
    align-content: space-around;
    box-sizing: border-box;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    justify-content: center;
    flex-wrap: nowrap;
    image {
      width: 100%;
      height: 100%;
    }
  }
  &-cover {
    width: 100%;
    position: absolute;
    left: 0;
    top: 0;
    transform: scale(0.12);
    &__icon {
      height: 100%;
      background: rgba(0, 0, 0, 0.2);
      position: relative;
      border-radius: 100%;
      &:after {
        content: "";
        display: block;
        padding-top: 100%;
      }
      &-inner {
        width: 100%;
        height: 100%;
        position: absolute;
        overflow: hidden;
        image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}
</style>
